package com.ag.oa.netty;

import com.ag.oa.redis.RedisUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.util.ResourceUtils;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

/**
 * netty服务
 */
public class NettyServer {

    // ssl文件存储位置
    private String sslKeyStore;
    // sll密码
    private String sslKeyPassword;
    // netty服务端口
    private int nettyPort;
    // netty合法来源
    private String nettyOrigin;
    // redis操作类
    private RedisUtils redisUtils;

    public NettyServer(String sslKeyStore, String sslKeyPassword, int nettyPort, String nettyOrigin, RedisUtils redisUtils) {
        this.sslKeyStore = sslKeyStore;
        this.sslKeyPassword = sslKeyPassword;
        this.nettyPort = nettyPort;
        this.nettyOrigin = nettyOrigin;
        this.redisUtils = redisUtils;
    }

    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            // 多个客户端同时连接，服务端不能处理的客户端连接请求放在队列中等待
            sb.option(ChannelOption.SO_BACKLOG, 1024);
            // 绑定线程池
            sb.group(bossGroup, workGroup)
                    // 指定使用Nio的channel
                    .channel(NioServerSocketChannel.class)
                    // 绑定监听端口
                    .localAddress(this.nettyPort)
                    // 绑定客户端连接时候触发操作
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("收到新连接");
                            // websocket协议本身是基于http协议的，所以这边也要使用http解编码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            // 对大数据流的支持
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            // 添加在线聊天消息处理类
                            ch.pipeline().addLast(new OnlineWebSocketHandler(nettyOrigin, redisUtils));
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/wss"
                                    , null, true, 65536 * 10));

                            // 以下为要支持wss所需处理
                            KeyStore ks = KeyStore.getInstance("JKS");
                            File jksFile = ResourceUtils.getFile(sslKeyStore);
                            InputStream jksInputStream = new FileInputStream(jksFile);
                            ks.load(jksInputStream, sslKeyPassword.toCharArray());
                            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                            kmf.init(ks, sslKeyPassword.toCharArray());
                            SSLContext sslContext = SSLContext.getInstance("TLS");
                            sslContext.init(kmf.getKeyManagers(), null, null);
                            SSLEngine sslEngine = sslContext.createSSLEngine();
                            // 是否使用客户端模式
                            sslEngine.setUseClientMode(false);
                            // 是否需要客户端校验
                            sslEngine.setNeedClientAuth(false);
                            // 需把SslHandler添加在第一位
                            ch.pipeline().addFirst("ssl", new SslHandler(sslEngine));
                        }
                    });
            // 服务器创建绑定，阻塞方式
            ChannelFuture cf = sb.bind().sync();
            System.out.println(NettyServer.class + " 启动正在监听： " + cf.channel().localAddress());
            // 关闭服务器通道，阻塞方式
            cf.channel().closeFuture().sync();
        } finally {
            // 释放线程池资源
            workGroup.shutdownGracefully().sync();
            bossGroup.shutdownGracefully().sync();
        }
    }
}
